package com.functionx.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;

public class HttpUtil {

    private static CloseableHttpClient httpClient = HttpClients.createDefault();
    // 配置请求参数实例
    private static RequestConfig requestConfig =
            RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                    .setSocketTimeout(60000)// 设置读取数据连接超时时间
                    .build();

    private static HttpResDataHandler convert2Bytes = entity -> {
        try {
            return EntityUtils.toByteArray(entity);
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return new byte[0];
        }
    };

    private static HttpResDataHandler convert2String = entity -> {
        try {
            return EntityUtils.toString(entity, Charset.defaultCharset());
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return "";
        }
    };

    public static byte[] doGetBytes(String url){
        return (byte[])doGet(url, convert2Bytes);
    }

    public static String doGet(String url) {
        return (String)doGet(url, convert2String);
    }

    public static byte[] doPostBytes(String url, Map<String, Object> paramMap) {
        return (byte[])doPost(url, paramMap, convert2Bytes);
    }

    public static byte[] doPostBytes(String url) {
        return (byte[])doPost(url, null, convert2Bytes);
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        return (String)doPost(url, paramMap, convert2String);
    }

    public static String doPost(String url) {
        return (String)doPost(url, null, convert2Bytes);
    }

    public static Object doGet(String url, HttpResDataHandler dataHandler) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            return dataHandler.dispose(entity);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Object doPost(String url, Map<String, Object> paramMap,
            HttpResDataHandler dataHandler) {
        HttpPost httpPost = new HttpPost(url);
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历，获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
            HttpEntity entity = httpResponse.getEntity();
            return dataHandler.dispose(entity);
        } catch (IOException e) {
            return null;
        }
    }

    interface HttpResDataHandler {
        Object dispose(HttpEntity entity);
    }

}
